package com.ruijie.acl.web.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.jsf.ListDataModel;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.ruijie.acl.AccessGroup;
import com.ruijie.acl.AclDevice;
import com.ruijie.acl.AclPlanInterface;
import com.ruijie.acl.AclPlanParameters;
import com.ruijie.acl.service.AccessGroupService;
import com.ruijie.acl.service.AclInterfaceService;
import com.ruijie.acl.service.AclPlanParametersService;
import com.ruijie.acl.type.AclPlanTypeEnum;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.acl.web.config.ui.AclDeployPlanUIParam;
import com.ruijie.acl.web.config.ui.DeployTimeAssignType;
import com.ruijie.batch.plan.AdhocPlan;
import com.ruijie.batch.plan.BatchPlan;
import com.ruijie.batch.plan.PlanDefinitionRequest;
import com.ruijie.batch.plan.PlanDefinitionService;
import com.ruijie.batch.plan.items.ExtendPlanDefinitionRequest;
import com.ruijie.batch.plan.items.ExtendPlanDefinitionService;
import com.ruijie.batch.plan.items.ItemParameters;
import com.ruijie.batch.task.Task;
import com.ruijie.batch.task.def.ItemParametersHandler;
import com.ruijie.batch.task.def.ParametersHandler;
import com.ruijie.emp.batch.web.DeviceExtendPlanDefinitionAction;
import com.ruijie.emp.components.deviceselector.TempDevice;
import com.ruijie.emp.components.deviceselector.service.DeviceSelectorService;
import com.ruijie.emp.components.deviceselector.web.DeviceSelector;
import com.ruijie.emp.device.Device;
import com.ruijie.emp.device.DeviceInterface;
import com.ruijie.emp.system.service.DeviceModelService;
import com.ruijie.foundation.bo.EntityObject;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.web.intercept.AddSuccessInfo;

/**
 * <p>
 * Title: ACL部署计划管理
 * </p>
 * <p>
 * Description: Function Description
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-09-21
 * </p>
 * 
 * @author ASAI
 *         <p>
 *         Update Time:
 *         </p>
 *         <p>
 *         Updater:
 *         </p>
 *         <p>
 *         Update Comments:
 *         </p>
 */
@Name("aclDeployPlanManagementAction")
@Scope(ScopeType.CONVERSATION)
@AddSuccessInfo
public class AclDeployPlanManagementAction extends DeviceExtendPlanDefinitionAction {

	private static String DEFAULT = "default";
	// 进入的类型
	// "planList" 计划列表
	// "planInterfaceList" 计划接口列表
	// "deviceDetail" 设备详细信息
	// "groupDetail" 组详细信息
	private String enterType = null;

	private boolean singleFlag = false;
	/**
	 * 是否为更新操作
	 */
	private boolean update = false;
	/*
	 * 上一个页面的地址
	 */
	private String prePage;

	private AclDeployPlanUIParam uiParam = new AclDeployPlanUIParam();

	// private AclPlanParamters aclPlanParamters;

	private List<AccessGroup> accessGroupList;

	private DeviceSelector deviceSelector;

	private AccessGroupSelector accessGroupSelector;

	private AclInterfaceProcessor aclInterfaceProcessor;

	private int selectedDeviceIndex = -1;

	// private ItemParametersHandler itemParametersHandler = new
	// AclDeployParametersHandler();

	@In("#{accessGroupService}")
	private AccessGroupService accessGroupService;

	@In("#{aclDeviceSelectorService}")
	private DeviceSelectorService aclDeviceSelectorService;

	@In("#{deviceModelService}")
	private DeviceModelService deviceModelService;

	@In("#{aclInterfaceService}")
	private AclInterfaceService aclInterfaceService;

	@In("#{aclPlanParametersService}")
	private AclPlanParametersService aclPlanParametersService;

	@In("#{aclDefaultExtendPlanDefinitionService}")
    private ExtendPlanDefinitionService aclExtendPlanDefinitionService;

	@Override
    public PlanDefinitionService getPlanDefinitionService() {
        return aclExtendPlanDefinitionService;
    }
	
	public AclInterfaceProcessor getAclInterfaceProcessor() {
		if (null == aclInterfaceProcessor)
			initAclInterfaceProcessor();

		return aclInterfaceProcessor;
	}

	public String getPrePage(){
		return this.prePage;
	}
	
	/**
	 * <p>
	 * Description: 初始化ACL接口处理器
	 * </p>
	 * <p>
	 * Create Time: 2009-09-22
	 * </p>
	 * 
	 * @author ASAI
	 */
	public void initAclInterfaceProcessor() {
		if (null == aclInterfaceProcessor) {
			aclInterfaceProcessor = new AclInterfaceProcessor(aclInterfaceService);
		}
	}

	public AccessGroupSelector getAccessGroupSelector() {
		if (null == accessGroupSelector)
			initAccessGroupSelector();

		return accessGroupSelector;
	}
	
	/*
	 * 获取选择的组
	 */
	@SuppressWarnings("unchecked")
	public List<AccessGroup> getSelectedAccessGroups(){
		List<Long> accessGroupIds = this.getAccessGroupSelector().getSelectedSelector()
		.getSelectedAccessGroupList();
		Page page = accessGroupService.pagedQuerySelectedAccessGroups(accessGroupIds
				.toArray(), 1, 10000);
		return (List<AccessGroup>) page.getResult();
	}

	/**
	 * <p>
	 * Description: 初始化组选择器
	 * </p>
	 * <p>
	 * Create Time: 2009-09-22
	 * </p>
	 * 
	 * @author ASAI
	 */
	public void initAccessGroupSelector() {
		if (null == accessGroupSelector) {
			accessGroupSelector = new AccessGroupSelector(accessGroupService);
		}
	}

	public DeviceSelector getDeviceSelector() {
		if (null == deviceSelector)
			initDeviceSelector();

		return deviceSelector;
	}

	/**
	 * <p>
	 * Description: 初始化设备选择器
	 * </p>
	 * <p>
	 * Create Time: 2009-09-22
	 * </p>
	 * 
	 * @author ASAI
	 */
	public void initDeviceSelector() {
		if (null == deviceSelector) {
			deviceSelector = new DeviceSelector(aclDeviceSelectorService, deviceModelService);
		}
	}

	@Override
	protected PlanDefinitionRequest instantizePlanDefinitionRequest() {
		PlanDefinitionRequest r = super.instantizePlanDefinitionRequest();
		initRequest(r);
		return r;
	}

	@Override
	protected PlanDefinitionRequest instantizePlanDefinitionRequest(BatchPlan selectedPlan) {
		PlanDefinitionRequest r = super.instantizePlanDefinitionRequest(selectedPlan);
		initRequest(r);
		return r;
	}

	@Override
	protected String getTargetTaskCode() {
		if (this.enterType.equals("planList")) {
			return Constants.ACL_DEPLOY_ACTION_TASK_CODE_MULTIPLE;
		} else {
			return Constants.ACL_DEPLOY_ACTION_TASK_CODE_DEPLOY_INTERFACE;
		}
	}

	@Override
	public String toAddPage() {
		setUpdate(false);
		return super.toAddPage();
	}

	@Override
	public String toUpdatePage(EntityObject model) {
		setUpdate(true);
		BatchPlan batchPlan = (BatchPlan) model;
		// 检测计划对象是否处于可修改状态
		getPlanDefinitionService().validateState(batchPlan, null);
		if (batchPlan.getTask().getCode().equals(Constants.ACL_DEPLOY_ACTION_TASK_CODE_MULTIPLE)) {
			this.enterType = "planList";
		} else {
			this.enterType = "planInterfaceList";
		}
		this.singleFlag = false;
		return super.toUpdatePage(model);
	}

	@Override
	protected String getAddPage() {
		this.selectedDeviceIndex = -1;
		return "/acl/plan/step1.seam";
	}

	/**
	 * <p>
	 * Description: 进入下发计划添加流程
	 * </p>
	 * <p>
	 * Create Time: 2008-12-15
	 * </p>
	 * 
	 * @author lusl
	 * @param softwareListEnter
	 *            是则标识为从软件列表页进入，否为从计划管理列表进入
	 * @return
	 */
	public String toAddMultiDeployPage(String enterType) {
		this.enterType = enterType;
		this.singleFlag = false;

		// 仅仅利用父类中初始化数据模型的部分
		toAddPage();

		setItemUIModel(null);
		this.getAccessGroupSelector().clearAllData();
		this.aclInterfaceProcessor=null;
		this.initAclInterfaceProcessor();
		return toStep1Page();
	}

	public String toStep1Page() {
		this.selectedDeviceIndex = -1;
		return "/acl/plan/step1.seam";
	}

	public String toStep2Page() {

			prepareItemParameters();

		// setItemUIModel(new HashMap<Long, Object>());
		return "/acl/plan/step2.seam";
	}

	public String toStep3Page() {
		this.selectedDeviceIndex = -1;
		if (this.enterType.equals("planInterfaceList")) {

				prepareItemParameters();

			
		}
		// 清空接口中的组下拉框
		this.accessGroupList = null;
		if (!this.isUpdate()) {
			setItemUIModel(new HashMap<Long, Object>());
		}
		return "/acl/plan/step3.seam";
	}

	public String toStep4Page(boolean isJump,String prePage) {
		this.prePage=prePage;
		if (!this.isUpdate()) {
			setItemUIModel(new HashMap<Long, Object>());
		}
		// 如果是第二步直接跳到第四步则清空接口
		if (isJump) {
			aclInterfaceProcessor = new AclInterfaceProcessor(aclInterfaceService);
		}
		return "/acl/plan/step4.seam";
	}

	public String toStep5Page() {
		this.checkDeployTime(this.uiParam);
		return "/acl/plan/step5.seam";
	}

	@Override
	protected String getDetailPage() {
		return "/acl/plan/planDetail.seam";
	}

	@Override
	protected String getListPage() {
		return "/acl/plan/planManagement.seam";
	}

	
	/**
	 * <p>
	 * Description: 检查部署下发时间设置
	 * </p>
	 * <p>
	 * Create Time: 2009-09-28
	 * </p>
	 * 
	 * @author ASAI
	 * @param uiParam
	 */
	protected void checkDeployTime(AclDeployPlanUIParam uiParam) {
		if (DeployTimeAssignType.PRECISION != uiParam.getDeployTimeAssignType()) {
			return;
		}
		
		if (uiParam.getDeployTime().before(new Date())) {
			throw new BusinessException("acl_deployment_plan_biz_check_deployTimeGTsystemTime");
		}
	}

	@Override
	protected String getUpdatePage() {
		// this.enterType = enterType;
		return toStep1Page();
	}

	/**
	 * <p>
	 * Description: 是否存在已选择设备
	 * </p>
	 * <p>
	 * Create Time: 2009-9-22
	 * </p>
	 * 
	 * @author ASAI
	 * @return
	 */
	public boolean containSelectedDevices() {
		return !getDeviceSelector().getAllSelectedDevices().isEmpty();
	}

	/**
	 * <p>
	 * Description: 是否存在已选择ACL组
	 * </p>
	 * <p>
	 * Create Time: 2009-9-22
	 * </p>
	 * 
	 * @author ASAI
	 * @return
	 */
	public boolean containSelectedAccessGroups() {
		return !getAccessGroupSelector().getSelectedSelector().getSelectedAccessGroupList()
				.isEmpty();
	}

	/**
	 * <p>
	 * Description: 是否已经配置接口应用
	 * </p>
	 * <p>
	 * Create Time: 2009-9-22
	 * </p>
	 * 
	 * @author ASAI
	 * @return
	 */
	public boolean containSelectedInterfaces() {
		return this.getAclInterfaceProcessor().isConfigFlag();
	}

	public List<AclPlanInterface> getAclPlanInterface(Device device) {
		if (device != null) {
			return this.getAclInterfaceProcessor().getInterfaceMap().get(device.getId());
		} else {
			return new ArrayList<AclPlanInterface>();
		}
	}

	@Override
	protected void prepareAddModel() {
		super.prepareAddModel();
		// aclPlanParamters = new AclPlanParamters();
		initUiParam();
	}

	private void initUiParam() {
		uiParam = new AclDeployPlanUIParam();
	}

	@Override
	public EntityObject getModel() {
		if (null == super.getModel()) {
			super.setModel(new AdhocPlan());
		}
		return super.getModel();
	}

	@Override
	protected void prepareUpdateModel() {
		super.prepareUpdateModel();
		this.singleFlag = false;
		AdhocPlan plan = (AdhocPlan) getModel();
		PlanDefinitionRequest req = prepareDefinitionRequest(plan);
		initUiParam();
		applyRequest2UIParams(uiParam, req);
		initItemUIModel(true);
	}

	@Override
	protected void prepareDetailModel() {
		super.prepareDetailModel();
		AdhocPlan plan = (AdhocPlan) getModel();
		PlanDefinitionRequest req = prepareDefinitionRequest(plan);
		initUiParam();
		applyRequest2UIParams(uiParam, req);
		initItemUIModel(false);
	}

	@Override
	public void resetModel() {
		super.resetModel();
		super.setModel(new AdhocPlan());
	}

	/**
	 * <p>
	 * Description: 在计划管理的界面上，保存和更新共用一个方法
	 * </p>
	 * <p>
	 * Create Time: 2009-09-24
	 * </p>
	 * 
	 * @author ASAI
	 * @return
	 */
	public String addOrUpdate() {
		if (isUpdate()) {
			this.saveAclPlanParameters();
			return update();
		}
		this.saveAclPlanParameters();
		return add();
	}

	@Override
	public String update() {
		// 显式指定当前为update操作
		getDefinitionRequest().setType(PlanDefinitionRequest.TYPE__UPDATE);
		return super.update();
	}

	/**
	 * 保存ACL部署计划的参数
	 */
	public void saveAclPlanParameters() {
		List<Device> deviceList = this.deviceSelector.getAllSelectedDevices();
		String updateParameters = "";
		for (Device device : deviceList) {
			AclPlanParameters aclPlanParameters = null;
			if (this.getItemUIModel().containsKey(device.getId())) {
				aclPlanParameters = aclPlanParametersService.get((Long) this.getItemUIModel().get(
						device.getId()));
			} else {
				aclPlanParameters = new AclPlanParameters();
			}
			aclPlanParameters.setDevice(device);
			List<AclPlanInterface> interfaceList = this.getAclInterfaceProcessor()
					.getInterfaceMap().get(device.getId());
			List<AclPlanInterface> interfaceLogList = null;
			if (interfaceList != null && interfaceList.size() > 0) {
				interfaceLogList = new ArrayList<AclPlanInterface>(interfaceList);
			}
			if (this.enterType.equals("planInterfaceList")) {
				aclPlanParameters.setDealType(AclPlanTypeEnum.AddInterface.toString());
				String accessGroupIds = "";
				if (interfaceList != null && interfaceList.size() > 0) {
					for (AclPlanInterface aclPlanInterface : interfaceList) {
						if (aclPlanInterface.getInAccessGroup() != null) {
							accessGroupIds += ","
									+ aclPlanInterface.getInAccessGroup().getId().toString();
						}
						if (aclPlanInterface.getOutAccessGroup() != null) {
							accessGroupIds += ","
									+ aclPlanInterface.getOutAccessGroup().getId().toString();
						}
					}
					if (!AclUtil.empty(accessGroupIds)) {
						aclPlanParameters.setAccessGroups(accessGroupIds.substring(1));
					}
				}
			} else {
				aclPlanParameters.setDealType(AclPlanTypeEnum.Add.toString());
				aclPlanParameters.setAccessGroups(this.getAccessGroupSelector()
						.convertGroupList2String());
				//[start]添加与选择的组相关联的接口，因为有些设备在删除组时会把接口部署信息也给删除掉，所以在部署组时也要重新同时部署与组相关的接口
				//获取要部署的组
				List<AccessGroup> accessGroups=this.getSelectedAccessGroups();
				if(accessGroups!=null&&accessGroups.size()>0){
					//根据设备和组列表，获取要重新部署的接口列表，返回AclPlanInterface的列表，与接口应用部署一致
					List<AclPlanInterface> aclPlanInterfaces=this.aclInterfaceService.getAclPlanInterfaces(device, accessGroups);
					//判断是否与继续接口应用选择的接口重复，重复以选择的接口为主，没有重复加入将要部署的接口列表
					if(aclPlanInterfaces!=null&&aclPlanInterfaces.size()>0){
						if(interfaceList != null && interfaceList.size() > 0){
							for(AclPlanInterface aclPlanInterface:aclPlanInterfaces){
								boolean repeat=false;
								//获取与组关联的接口信息
								DeviceInterface reDeployInterface=aclPlanInterface.getDeviceInterface();
								AccessGroup inAccessGroup=aclPlanInterface.getInAccessGroup();
								AccessGroup outAccessGroup=aclPlanInterface.getOutAccessGroup();
								for(int i=0;i<interfaceList.size();i++){
									//获取用户选择的接口信息
									AclPlanInterface selectedInterface=interfaceList.get(i);
									if(selectedInterface.getDeviceInterface().equals(reDeployInterface)){
										//接口重复，以下进行是否要添加接口部署信息操作
										if(selectedInterface.getInAccessGroup()==null){
											//修改用户选择的接口，添加in方向的部署
											selectedInterface.setInAccessGroup(inAccessGroup);
											repeat=true;
										}
										if(selectedInterface.getOutAccessGroup()==null){
											//修改用户选择的接口，添加out方向的部署
											selectedInterface.setOutAccessGroup(outAccessGroup);
											repeat=true;
										}
									}
									if(repeat){
										break;
									}
								}
								if(!repeat){
									//没有与接口应用部署中的接口重复，加入接口部署列表
									interfaceList.add(aclPlanInterface);
								}
							}
						}else{
							//用户没有选择继续接口部署应用，将所有与组关联的接口，添加到接口部署列表中
							interfaceList=new ArrayList<AclPlanInterface>(aclPlanInterfaces);
						}
					}
				}
				//[end]
			}
			// aclPlanParameters.setBatchPlan((BatchPlan)this.getModel());
			if (interfaceList != null && interfaceList.size() > 0) {
				String interfaceParam = this.getAclInterfaceProcessor()
						.convertAclPlanInterface2String(interfaceList);
				aclPlanParameters.setInterfaces(interfaceParam);
			}else{
				aclPlanParameters.setInterfaces("");
			}
			if(interfaceLogList!=null && interfaceLogList.size()>0){
				String interfaceParamLog = this.getAclInterfaceProcessor()
				.convertAclPlanInterface2String(interfaceLogList);
				aclPlanParameters.setInterfacesLog(interfaceParamLog);
			}else{
				aclPlanParameters.setInterfacesLog("");
			}
			aclPlanParametersService.save(aclPlanParameters);
			this.getItemUIModel().put(device.getId(), aclPlanParameters.getId());
			updateParameters += "," + aclPlanParameters.getId();
		}

		updateParameters += ",";
		String deleteIds = "";
		// 如果为更新，则删除没有选择选择的参数对象
		if (this.isUpdate()) {
			Collection<Object> values = this.getItemUIModel().values();
			for (Object obj : values) {
				String paramId = obj.toString();
				if (updateParameters.indexOf("," + paramId + ",") == -1) {
					deleteIds += "," + paramId;
				}
			}
			if (!AclUtil.empty(deleteIds)) {
				deleteIds = deleteIds.substring(1);
				aclPlanParametersService.removeByIds(deleteIds);
			}
		}
		
	}

	@Override
	protected void populateDefinitionRequest(PlanDefinitionRequest definitionRequest) {
		super.populateDefinitionRequest(definitionRequest);
		applyUIParams2Request(uiParam, definitionRequest);
	}

	/**
	 * <p>
	 * Description: 将界面参数应用到计划请求对象的相关属性上
	 * </p>
	 * <p>
	 * Create Time: 2009-09-24
	 * </p>
	 * 
	 * @author ASAI
	 * @param ui
	 *            界面参数对象
	 * @param req
	 *            计划请求对象
	 */
	@SuppressWarnings("unchecked")
	private void applyUIParams2Request(AclDeployPlanUIParam ui, PlanDefinitionRequest req) {
		Assert.notNull(ui);
		Assert.notNull(req);

		if (!req.isUpdate()) {
			req.asAhdocPlan();
		}

		switch (ui.getDeployTimeAssignType()) {
		case RIGHTNOW:
			req.removeStepSchedule(DEFAULT);
			break;
		case PRECISION:
			req.applyStepScheduledAt(DEFAULT, ui.getDeployTime());
			break;
		}

		// 遇错继续下一个设备
		req.applyIgnoreException();

		// 串行
		req.applySimpleProcess();

		ExtendPlanDefinitionRequest request = (ExtendPlanDefinitionRequest) req;
		Collection itemParameters = request.getItemParameters();
		if (!CollectionUtils.isEmpty(itemParameters)) {
			for (Object entry : itemParameters) {
				TempDevice item = (TempDevice) ((Object[]) entry)[0];
				ItemParameters parameters = (ItemParameters) ((Object[]) entry)[1];
				if (parameters == null) {
					parameters = new ItemParameters();
					((Object[]) entry)[1] = parameters;
				}
				parameters.setItem(item.getReal().getId());
				parameters.putParameter(Constants.ACL_DEPLOY_PLAN_ITEM_PARAM_NAME, this
						.getItemUIModel().get(item.getReal().getId()).toString());
			}
		}
	}

	/**
	 * <p>
	 * Description:将计划请求对象的相关属性应用到界面参数上
	 * </p>
	 * <p>
	 * Create Time: 2009-09-28
	 * </p>
	 * 
	 * @author ASAI
	 * @param uiParam
	 * @param req
	 */
	protected void applyRequest2UIParams(AclDeployPlanUIParam uiParam, PlanDefinitionRequest req) {
		if (req.isAtType(DEFAULT)) {
			uiParam.setDeployTimeAssignType(DeployTimeAssignType.PRECISION);
			uiParam.setDeployTime(req.getStepScheduledAtValue(DEFAULT));
		} else {
			uiParam.setDeployTimeAssignType(DeployTimeAssignType.RIGHTNOW);
		}
	}

	/**
	 * <p>
	 * Description: 初始化所有需要检查的设备对应的参数
	 * </p>
	 * <p>
	 * Create Time: 2009-09-27
	 * </p>
	 * 
	 * @author ASAI
	 */
	@SuppressWarnings("unchecked")
	private void initItemUIModel(boolean paramFlag) {
		setItemUIModel(new HashMap());
		ExtendPlanDefinitionRequest request = (ExtendPlanDefinitionRequest) getDefinitionRequest();
		
			((ExtendPlanDefinitionService) getPlanDefinitionService())
					.populateExtendDefinitionRequest(request);
			Collection itemParameters = request.getItemParameters();
			boolean isFirst = true;
			for (Object entry : itemParameters) {
				TempDevice item = (TempDevice) ((Object[]) entry)[0];
				ItemParameters parameters = (ItemParameters) ((Object[]) entry)[1];
				if (parameters == null) {
					parameters = new ItemParameters();
					((Object[]) entry)[1] = parameters;
				}
				String id = parameters.getParameterValue(Constants.ACL_DEPLOY_PLAN_ITEM_PARAM_NAME);
				if (StringUtils.hasText(id)) {
					AclPlanParameters aclPlanParameters = aclPlanParametersService.get(Long
							.parseLong(id));
					// 
					if (paramFlag) {
						// 组信息只设置一次
						if (isFirst) {
							// 设置ACL组列表
							this.getAccessGroupSelector().getSelectedSelector()
									.setSelectedAccessGroupList(
											this.getAccessGroupSelector().convertString2GroupList(
													aclPlanParameters.getAccessGroups()));
							isFirst = false;
						}
						// 设置接口列表
						List<AclPlanInterface> interfaceList = this.getAclInterfaceProcessor()
								.convertString2AclPlanInterface(aclPlanParameters.getInterfaces());
						this.getAclInterfaceProcessor().getInterfaceMap().put(item.getReal().getId(),
								interfaceList);
					}
					this.getItemUIModel().put(item.getReal().getId(), aclPlanParameters.getId());
				}
				// getItemUIModel().put(item.getReal().getId(), value);
			}

	}

	@SuppressWarnings("unchecked")
	public List<AccessGroup> getAccessGroupList() {
		// "planList" 计划列表
		if (this.enterType.equals("planList")) {
			List<Long> accessGroupIds = this.getAccessGroupSelector().getSelectedSelector()
					.getSelectedAccessGroupList();
			if (this.accessGroupList == null && accessGroupIds.size() > 0) {
				Page page = accessGroupService.pagedQuerySelectedAccessGroups(accessGroupIds
						.toArray(), 1, 10000);
				this.accessGroupList = (List<AccessGroup>) page.getResult();
			}
		}
		// "planInterfaceList" 计划接口列表
		if (this.enterType.equals("planInterfaceList")) {
			if (this.getAclInterfaceProcessor().getDevice() != null) {
				this.accessGroupList = accessGroupService.findByDevice(getAclInterfaceProcessor()
						.getDevice());
			}
		}
		// "deviceDetail" 设备详细信息
		else if (this.enterType.equals("deviceDetail")) {

		}
		// "groupDetail" 组详细信息
		return this.accessGroupList;
	}

	public boolean isShowAccessGroup() {
		if (this.getEnterType().equals("planInterfaceList")) {
			return false;
		}
		return true;
	}

	/**
	 * 取得当前选择设备的顺序号
	 * 
	 * @param device
	 *            设备
	 * @return
	 */
	private int getCurrentDeviceIndex(Device device) {
		if (device != null) {
			List<Device> deviceList = this.getDeviceSelector().getAllSelectedDevices();
			for (int i = 0; i < deviceList.size(); i++) {
				Device tDevice = deviceList.get(i);
				if (tDevice.getId().longValue() == device.getId().longValue()) {
					this.selectedDeviceIndex = i;
					return this.selectedDeviceIndex;
				}
			}
		}
		this.selectedDeviceIndex = -1;
		return this.selectedDeviceIndex;
	}

	/**
	 * 是否存在下一个设备
	 * 
	 * @param device
	 * @return
	 */
	public boolean hasNextDevice(Device device) {
		if (this.selectedDeviceIndex == -1) {
			this.getCurrentDeviceIndex(device);
		}
		if (this.selectedDeviceIndex == -1
				|| this.selectedDeviceIndex + 1 >= this.getDeviceSelector().getAllSelectedDevices()
						.size()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 是否存在上一个设备
	 * 
	 * @param device
	 * @return
	 */
	public boolean hasPreviousDevice(Device device) {
		if (this.selectedDeviceIndex == -1) {
			this.getCurrentDeviceIndex(device);
		}
		if (this.selectedDeviceIndex == -1 || this.selectedDeviceIndex - 1 < 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 下一个设备
	 * 
	 * @param device
	 */
	public void nextDevice(Device device) {
		if (this.hasNextDevice(device)) {
			this.getAclInterfaceProcessor().save();
			this.getAclInterfaceProcessor().changeDevice(
					this.getDeviceSelector().getAllSelectedDevices().get(
							this.selectedDeviceIndex + 1));
			this.selectedDeviceIndex++;
		}
	}

	/**
	 * 上一个设备
	 * 
	 * @param device
	 */
	public void previousDevice(Device device) {
		if (this.hasPreviousDevice(device)) {
			this.getAclInterfaceProcessor().save();
			this.getAclInterfaceProcessor().changeDevice(
					this.getDeviceSelector().getAllSelectedDevices().get(
							this.selectedDeviceIndex - 1));
			this.selectedDeviceIndex--;
		}
	}

	/**
	 * 改变设备
	 * 
	 * @param device
	 */
	public void changeDevice(Device device) {
		this.changeDevice(device, false);
	}

	/**
	 * 改变设备
	 * 
	 * @param device
	 * @param isSave 是否要保存
	 */
	@AddSuccessInfo
	public void changeDevice(Device device, boolean isSave) {
		if (isSave) {
			this.getAclInterfaceProcessor().save();
		}
		this.getCurrentDeviceIndex(device);
		this.getAclInterfaceProcessor().changeDevice(device);
	}

	/**
	 * 改变设备
	 * 
	 * @param device
	 */
	public void saveInterfaceAccessGroup(Device device) {
		this.getAclInterfaceProcessor().save();
	}

	@Override
	protected Page pagedQuery(EntityObject criteria, int page, int pageSize) {
		BatchPlan searchPlan = (BatchPlan) criteria;
		if (searchPlan.getTask() == null) {
			Task task = new Task();
			task.setCode(Constants.ACL_DEPLOY_ACTION_TASK_CODE_PREX);
			searchPlan.setTask(task);
		}
		return super.pagedQuery(searchPlan, page, pageSize);
	}

	@Override
	@Transactional
	public String startPlan(BatchPlan plan) {
		// 检测是否已经过期
		ExtendPlanDefinitionRequest request = (ExtendPlanDefinitionRequest) instantizePlanDefinitionRequest(plan);
		if (request.isAtType(DEFAULT)) {
			Date deployTime = request.getStepScheduledAtValue(DEFAULT);
			if (deployTime.before(new Date())) {
				throw new BusinessException("acl_deployment_plan_check_deployTimeGTsystemTime");
			}
		}
		
		submit(plan);
        this.setEntityList(new ArrayList<EntityObject>());
        updateModel();
        addGlobalI18nMessage("batch_plan_start_plan_success");
        return getListPage();
		//return super.startPlan(plan);
	}
	/*
	 * 获取数据列表
	 */
	@SuppressWarnings("unchecked")
	public ListDataModel getEntityList(boolean setNull) {
		if(setNull){
			return super.getEntityList();
		}else{
			currentPage = pagedQuery(prepareCriteria(getCriteria()), page, pageSize);
	        logger.debug("got entity list size:" + currentPage.getTotalCount());
	        List<EntityObject> entityList = (List<EntityObject>) currentPage.getResult();
	        selectedIds.clear();
	        this.setEntityList(entityList);
	        return new ListDataModel(entityList);
		}
    }

    /**
     * 停止
     * @return
     */
    @Transactional
    public String stopPlan(BatchPlan plan) {
        stop(plan);
        this.setEntityList(new ArrayList<EntityObject>());
        updateModel();
        addGlobalI18nMessage("batch_plan_stop_plan_success");
        return getListPage();
    }
	
	/**
	 * 删除计划
	 */
	@SuppressWarnings("unchecked")
	public String deletePlan(BatchPlan plan) {
		ExtendPlanDefinitionRequest request = (ExtendPlanDefinitionRequest) prepareDefinitionRequest(plan);
		((ExtendPlanDefinitionService) getPlanDefinitionService())
				.populateExtendDefinitionRequest(request);
		Collection itemParameters = request.getItemParameters();
		String deleteIds = "";
		for (Object entry : itemParameters) {
			ItemParameters parameters = (ItemParameters) ((Object[]) entry)[1];
			if (parameters == null) {
				parameters = new ItemParameters();
				((Object[]) entry)[1] = parameters;
			}
			String id = parameters.getParameterValue(Constants.ACL_DEPLOY_PLAN_ITEM_PARAM_NAME);
			if (StringUtils.hasText(id)) {
				deleteIds += "," + id;
			}
		}
		getPlanDefinitionService().removeBatchPlan(
				this.getPlanDefinitionService().getBatchPlan(plan.getId()));
		if (!AclUtil.empty(deleteIds)) {
			deleteIds = deleteIds.substring(1);
			aclPlanParametersService.removeByIds(deleteIds);
		}
		list();
		facesMessages.add(getDelSingleSuccessMsg());
		return getListPage();
	}

	public String getEnterType() {
		return enterType;
	}

	public void setEnterType(String enterType) {
		this.enterType = enterType;
	}

	public AclDeployPlanUIParam getUiParam() {
		return uiParam;
	}

	public void setUiParam(AclDeployPlanUIParam uiParam) {
		this.uiParam = uiParam;
	}

	private void setUpdate(boolean update) {
		this.update = update;
	}

	public boolean isUpdate() {
		return update;
	}

	@Override
	protected ItemParametersHandler getItemParametersHandler() {
		return null;
	}

	@Override
	protected ParametersHandler getParametersHandler() {
		return null;
	}

	private boolean deviceBtnDisplay = true;
	private boolean accessGroupBtnDisplay = true;

	public boolean isDeviceBtnDisplay() {
		return deviceBtnDisplay;
	}

	public void setDeviceBtnDisplay(boolean deviceBtnDisplay) {
		this.deviceBtnDisplay = deviceBtnDisplay;
	}

	public boolean isAccessGroupBtnDisplay() {
		return accessGroupBtnDisplay;
	}

	public void setAccessGroupBtnDisplay(boolean accessGroupBtnDisplay) {
		this.accessGroupBtnDisplay = accessGroupBtnDisplay;
	}

	public boolean isSingleFlag() {
		return singleFlag;
	}

	public void setSingleFlag(boolean singleFlag) {
		this.singleFlag = singleFlag;
	}

	/**
	 * 跳转到部署页面(单ACL设备,多ACL组,ACL设备不可添加修改删除)
	 * 
	 * @param aclDevice
	 *            ACL设备
	 * @param accessGroupList
	 *            ACL组列表
	 */
	public void jump2Deploy(AclDevice aclDevice, List<AccessGroup> accessGroupList) {
		List<AclDevice> aclDeviceList = new ArrayList<AclDevice>();
		aclDeviceList.add(aclDevice);
		singleFlag = false;
		this.jump2Deploy(aclDeviceList, false, null, true);
	}

	/**
	 * 跳转到部署页面(单ACL组,多ACL设备,ACL组不可添加修改删除)
	 * 
	 * @param aclDeviceList
	 *            ACL设备列表
	 * @param accessGroupList
	 *            ACL组列表
	 */
	public void jump2Deploy(List<AclDevice> aclDeviceList, AccessGroup accessGroup) {
		List<AccessGroup> accessGroupList = new ArrayList<AccessGroup>();
		accessGroupList.add(accessGroup);
		singleFlag = true;
		this.jump2Deploy(null, true, accessGroupList, false);
	}

	/**
	 * 跳转到部署页面
	 * 
	 * @param aclDeviceList
	 *            ACL设备列表
	 * @param deviceBtnDisplay
	 *            是否显示ACL设备导入界面的按钮
	 * @param accessGroupList
	 *            ACL组列表
	 * @param accessGroupBtnDisplay
	 *            是否显示ACL组导入界面的按钮
	 */
	public void jump2Deploy(List<AclDevice> aclDeviceList, boolean deviceBtnDisplay,
			List<AccessGroup> accessGroupList, boolean accessGroupBtnDisplay) {
		prepareAddModel();
		this.setUpdate(false);
		this.enterType = "planList";
		// 设备ID设置
		if (aclDeviceList != null && aclDeviceList.size() > 0) {
			List<Long> ids = new ArrayList<Long>();
			for (AclDevice entity : aclDeviceList) {
				ids.add(entity.getDevice().getId());
			}
			this.getDeviceSelector().getAvailableSelector().select(
					ids.toArray(new Long[ids.size()]));
		}
		this.deviceBtnDisplay = deviceBtnDisplay;
		this.redirectTo(this.getAddPage());

		// ACL组设置
		if (accessGroupList != null && accessGroupList.size() > 0) {
			List<Long> ids = new ArrayList<Long>();
			for (AccessGroup entity : accessGroupList) {
				ids.add(entity.getId());
			}
			this.getAccessGroupSelector().getSelectedSelector().setSelectedAccessGroupList(ids);
		}
		this.accessGroupBtnDisplay = accessGroupBtnDisplay;
		this.redirectTo(toStep1Page());
		// return this.toStep1Page();
	}
}
